package com.tecode.myBooks.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 数据库链接类
 * @author Administrator
 *
 */
public class DBUtil {
	
	private final static String USER_NAME;
	private final static String PASSWORD;
	private final static String URL;
	private final static String DRIVER;
	
	static{
		Properties pro = new Properties();
		
		try {
			pro.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		USER_NAME = pro.getProperty("mysql.username");
		PASSWORD = pro.getProperty("mysql.pwd");
		URL = pro.getProperty("mysql.url");
		DRIVER = pro.getProperty("mysql.driver");
		
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	public static Connection getConnection(){
		
		
		Connection conn = null;
		
		try {
			conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
			//手动抛出异常
			throw new RuntimeException(e.getMessage());
		}
		return conn;
	}
	
	/**
	 * 关闭链接
	 * @param conn
	 * @param st
	 * @param rs
	 */
	public static void close(Connection conn,Statement st,ResultSet rs){		
		
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(st != null){
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
